<template>
  <t-dialog
    header="修改用例信息"
    :visible.sync="showDialog"
    @confirm="onConfirm"
    :confirmOnEnter="true"
    :onConfirm="onConfirmAnother"
    :onCancel="onCancel"
    :onEscKeydown="onKeydownEsc"
    :onCloseBtnClick="onClickCloseBtn"
    :onOverlayClick="onClickOverlay"
    :onClose="close"
    width='50%'
  >
  <!-- <t-select>
    :popup-props="{ 'on-scroll-to-bottom': handleScrollToBottom }"
  </t-select> -->
  <t-space size="32px">
  <t-form
    :data="formData"
    labelWidth="calc(2em + 50px)"
    :layout="layout"
    ref="form"
    @reset="onReset"
    @submit="onSubmit"
    scrollToFirstError="smooth"
  >
      <t-form-item label="所属模块" name="module">
          <t-select
            v-model="formData.module"
            :style="{ width: '222px' }"
            class="demo-select-base"
            placeholder="请选择类型"
            clearable
          >
          <t-option v-for="(item, index) in MODULES_OPTIONS" :key="index + item.path" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>

      <t-form-item label="迭代版本" name="testcase_version" layout="inline">
        <t-select
          v-model="formData.testcase_version"
          :style="{ width: '222px' }"
          placeholder="请选择"
          class="demo-select-base"
          :options="testCaseVersionM"
          :keys="{ label: 'sprint_name', value: 'sprint_id' }"
          clearable
          >
          <!-- <t-option v-for="(item, index) in TESTCASE_VERSION_OPTIONS" :key="index + item.path" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option> -->
        </t-select>
      </t-form-item>
      <t-form-item label="优先级" name="priority">
        <t-space size="10px">
          <t-check-tag theme="primary" size="large" :plain="item.checked == true ? false : true"
          v-for="(item , index) in priorityCheck" :key="index" @click="clickPriority(item)" v-model="item.checked">{{item.label}}
          </t-check-tag>
        </t-space>
      </t-form-item>
      <t-form-item label="标签" name="tags">
                <t-select
                  v-model="formData.testcase_tags"
                  class="form-item-content"
                  placeholder="请选择标签"
                  :options="testCaseTagsM"
                  :keys="{ label: 'tag_name', value: 'tag_id' }"
                  multiple
                  :minCollapsedNum="3"
                  @change="handleChange"
                  id="tags"
                  :style="{ minWidth: '134px' }"
                />               
              </t-form-item>

      <!-- <template>
        支持自定义标签，以后可能会用到
        <t-form-item label="标签" name="testcase_tags">
          <t-space style="width: 150%">
            <t-tag-input v-model="formData.testcase_tags"
            :min-collapsed-num="3"
            :autoWidth="true"
            placeholder="请输入标签                                                  "
            status="success"
            >
              <template #collapsedItems="{ collapsedTags }">
                <t-popup>
                  <t-tag>More({{ collapsedTags.length }})</t-tag>
                  <template #content>
                    <t-tag v-for="item in collapsedTags" :key="item" style="margin-right: 40px">
                    {{ item }}
                    </t-tag>
                  </template>
                </t-popup>
              </template>
            </t-tag-input>
          </t-space>
        </t-form-item>
      </template> -->
      <t-form-item label="测试用例" style="margin-top: 20px;">
        <t-input v-model="formData.testcase_name" placeholder="请输入测试名称" style="margin-right: 10px;"></t-input>
        <t-input v-model="formData.git_addr"  placeholder="请输入测试用例地址" ></t-input>
      </t-form-item>    
    </t-form>
  </t-space>
  </t-dialog>
</template>

<script lang="jsx">
import { Icon } from 'tdesign-icons-vue';
import { Tag } from 'tdesign-vue';
import { getTestCaseInfo, operateTestCase } from '@/api/requestApi';

// import { CheckCircleFilledIcon, ErrorCircleFilledIcon, CloseCircleFilledIcon, Icon } from 'tdesign-icons-vue';
import {
  MODULES_OPTIONS,
  TESTCASE_PRIORITY_OPTIONS,
} from '@/constants';
import { TypeFormatFlags } from 'typescript';

const INITIAL_FORM_DATA = {
  testcase_name: '',
  testcase_tags: [],
  testcase_version: '',
  module: undefined,
  priority: undefined,
  git_addr: '',
};
const FORM_RULES = {
  testcase_name: [{ required: true, message: '请输入用例名称', type: 'error' }],
  testcase_version: [{ required: true, message: '请选择版本', type: 'error' }],
  module: [{ required: true, message: '请选择所属模块', type: 'error' }],
  priority: [{ required: true, message: '请选择优先级', type: 'error' }],
  git_addr: [{ required: true, message: '请输入用例地址', type: 'error' }],
};

export default {
  name: 'ModifyDialogComp',
  components: {
  },
  props: {
    showChildDialog: {
      type: Boolean,
      default: false
    },
    testCaseTagsM: Array,
    testCaseVersionM: Array,
  },
  data() {
    return {    
      MODULES_OPTIONS,
      layout: 'vertical', // 纵向布局
      formData: {...INITIAL_FORM_DATA},
      FORM_RULES: {...FORM_RULES},
      priorityCheckArr: [],
      priorityCheck: TESTCASE_PRIORITY_OPTIONS,
      testcase_tags: [],
      // renderCollapsedItems 支持自定义标签
      // renderCollapsedItems: (_, { collapsedTags }) => <Tag>更多({collapsedTags.length})</Tag>,
    };
  },
  
  computed: {
    showDialog: {
      get() {
        return this.showChildDialog
      },
      set(newValue) {
        this.$emit('update:showChildDialog', newValue) // 触发更新事件，父组件的showDialogAdd会自动更新
      }
    },
  },
  mounted() {
    // this.$refs.formValidatorStatus.validate();
    // this.dataLoading = true;
    
  },
  methods: {
    init(data) {

      // console.log('来自父组件的->', data)
      // 根据testcase_id 获取测试用例信息
      const idx = data.testcase_id.toString();
      this.$request
        .get(`${getTestCaseInfo()}?testcase_id=${idx}`)
        .then((res) => {         
          if (res.data.code === '000') {
            this.formData = res.data.data
            // console.log('priority->',this.formData.priority)
            console.log('c查看 tags--->?',this.formData)
            this.priorityCheck.forEach(elment =>{
              elment.checked = false;
              if (elment.value === this.formData.priority){
                // console.log('来自父组件的', this.formData);
                elment.checked = true;
              }
            })
          } else {
            this.$message.error(res.data.msg);
          }     
        })
        .catch((e) => {
          this.$message.error('系统异常');
          console.log(e)
          
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    onConfirm() {
      console.log(this.formData)
      const reqParam = {"ids": [], "param": [{}], "op_type": ''};
      // console.log('c查看 tags--->?',this.formData)
      // const selectTags = []
      const selectTags = this.formData.testcase_tags.map((tag) => {
        if (typeof tag === 'number') {
          const item = this.testCaseTagsM.find((obj) => obj.tag_id === tag)
          return item ? item.tag_name : null;
        }
        return tag;
      });
      // const selectTags = this.formData.testcase_tags.map((tag) => {
      //   if (tag === 'number'){
      //     const item = this.testCaseTagsM.find((obj) => obj.tag_id === tag);
      //     return item ? item.tag_name : null;
      //   }
      // })
      reqParam.param[0].testcase_name = this.formData.testcase_name;
      reqParam.param[0].testcase_version = this.formData.testcase_version;
      reqParam.param[0].testcase_tags = selectTags;
      reqParam.param[0].priority = this.formData.priority;
      reqParam.param[0].git_addr = this.formData.git_addr;
      reqParam.param[0].module = this.formData.module.toString();
      reqParam.op_type = '2';
      reqParam.ids.push(this.formData.testcase_id.toString());
      // console.log('c查看 tags--->?',this.formData)
      this.$request
        .post(operateTestCase(),reqParam)
        .then((res) => {
          if (res.data.code === '000') {
            this.$message.success('测试用例修改成功');
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      this.showDialog = false;
    },
    clickPriority(item){
      // console.log('aaaa11',item.label,item.checked)
      this.priorityCheck.forEach(elment =>{
        elment.checked = false;
      })
      this.priorityCheckArr.splice(0, 1)
      this.priorityCheckArr.push(item.value)
      this.formData.priority =item.value
    },
    changePriority(){
      // console.log('changePriority')
    },
    onConfirmAnother() {
      // console.log('点击了确认按钮111', context);
      // this.$emit('modifyFlush')
    },
    close() {
      this.showDialog = false;
      // console.log('关闭弹窗，点击关闭按钮、按下ESC、点击蒙层等触发', context);
    },
    onCancel() {
      this.showDialog = false;
      // console.log('点击了取消按钮', context);
    },
    onKeydownEsc() {
      // console.log('按下了ESC', context);
    },
    onClickCloseBtn() {
      // console.log('点击了关闭按钮', context);
    },
    onClickOverlay() {
      // console.log('点击了蒙层', context);
    },
    onReset(data) {
      console.log(data);
    },
    onSubmit(result, firstError) {
      if (!firstError) {
        this.$message.success('提交成功');
        this.formVisible = false;
      } else {
        this.$message.warning(firstError);
      }
    },
    handleChange(args) {
      console.log('change', ...args);
    },
  },
  
};
</script>

<style lang="less" scoped>
@import '@/style/variables.less';

/deep/ [class*='t-table-expandable-icon-cell'] .t-icon {
  background-color: transparent;
}


.t-button + .t-button {
  margin-left: var(--td-comp-margin-s);
}
.t-button {
  margin-right: 20px;
}
.tdesign-demo-form-status .t-input {
  width: 520px;
}

</style>